package com.my.stock.core;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;

public class Hurst {

	public static void main(String[] args) throws IOException {

//		double p[] = { 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0 };
//		c(p);
//		
//		double p[]=new double[100];
//		for(int i=0;i<p.length;i++) {
//			p[i]=Math.random();
//			
//		}
//		c(p);

		double p[] = new double[257];
		for (int i = 0; i < p.length; i++) {
			p[i] = (i + 1) * 2 + 100;

		}
		c(p);

	}

	public static double[] linearFit(List<Double> x, List<Double> y) {
		if (x.size() != y.size()) {
			throw new IllegalArgumentException("输入的 x 和 y 数组长度必须相同");
		}

		int n = x.size();
		double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;

		// 计算总和
		for (int i = 0; i < n; i++) {
			sumX += x.get(i);
			sumY += y.get(i);
			sumXY += x.get(i) * y.get(i);
			sumX2 += x.get(i) * x.get(i);
		}

		// 计算平均值
		double meanX = sumX / n;
		double meanY = sumY / n;

		// 计算斜率 a
		double numerator = sumXY - n * meanX * meanY;
		double denominator = sumX2 - n * meanX * meanX;
		double a = numerator / denominator;

		// 计算截距 b
		double b = meanY - a * meanX;

		return new double[] { a, b };
	}

	public static void c(double p[]) {
		double lastSD = 0;
		int c = 0;
		List<Double> xlist = new ArrayList<Double>();
		List<Double> ylist = new ArrayList<Double>();
		for (int i = 3; i < p.length / 2 + 1; i++) {

			if (i != 3 && i != 5 && i != 9 && i != 17 && i != 33 && i != 65 && i != 129 && i != 257) {
				continue;
			}

			DescriptiveStatistics rsSTD = new DescriptiveStatistics();

			for (int j = 0; j < p.length - i + 1; j++) {

				DescriptiveStatistics dss = new DescriptiveStatistics();
				DescriptiveStatistics ds = new DescriptiveStatistics();
				for (int k = j; k < j + i; k++) {

					ds.addValue(p[k]);

				}
				for (int k = j; k < j + i; k++) {
					dss.addValue(ds.getMean() - p[k]);
				}
				double std = ds.getStandardDeviation();
				double rs = (dss.getMax() - dss.getMin()) / std;
				System.out.println(i + " " + rs);
				rsSTD.addValue(rs);

			}
//			System.out.print(lastSD - rsSTD.getStandardDeviation() + " ");
			xlist.add(Math.log(i - 1));
			ylist.add(Math.log(rsSTD.getMean()));
//			System.out.print(Math.log(rsSTD.getMean()) / Math.log(i) + " ");
//			System.out.print(rsSTD.getMean() + " ");
		}
		double[] d=linearFit(xlist, ylist);
		System.out.println(d[0]);
		System.out.println(d[1]);
//		System.out.println(c);

	}

}
